/*
 * Copyright 2007 Agile Plugins Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 	http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.agileplugins.cruisewatcher;

import com.intellij.ui.PanelWithButtons;
import com.intellij.util.ui.Table;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class CruiseWatcherConfigurationTablePanel extends PanelWithButtons {
    private JButton addButton;
    private JButton removeButton;
    private CruiseWatcherTableModel tableModel;
    private Table table;

    public CruiseWatcherConfigurationTablePanel(CruiseWatcherTableModel tableModel) {
        this.tableModel = tableModel;
        this.table = new Table(tableModel);
        table.setSelectionMode(0);
        initPanel();
    }

    public void stopEditing() {
        if (table.isEditing()) {
            table.getCellEditor().stopCellEditing();
        }
    }

    protected String getLabelText() {
        return "CruiseWatcher Configuration";
    }

    protected JButton[] createButtons() {
        addButton = new JButton("Insert");
        addButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent actionEvent) {
                doAdd();
            }
        });
        removeButton = new JButton("Remove");
        removeButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent actionEvent) {
                doRemove();
            }
        });
        return new JButton[]{addButton, removeButton};
    }

    protected JComponent createMainComponent() {
        return new JScrollPane(table);
    }

    private void doAdd() {
        stopEditing();
        int selectedRow = table.getSelectedRow();
        tableModel.addRow(selectedRow);
    }

    private void doRemove() {
        stopEditing();
        int selectedRow = table.getSelectedRow();
        tableModel.removeRow(selectedRow);
        table.getSelectionModel().setSelectionInterval(selectedRow, selectedRow);
    }
}


